<?php

class FP_Image_Thumbnail extends FP_Image {

    protected $owidth = null;
    protected $oheight = null;

    public function __construct($pFile, $pWidth, $pHeight, $pCropRatio, array $pOptions=array()){

	logdebug("FP_Image_Thumbnail.__construct: $pFile $pWidth x $pHeight $pCropRatio");

	if (array_key_exists('cachedir', $pOptions)){
	    if (!array_key_exists('cacheid', $pOptions))
		throw new Exception('Missing cacheid parameter');

	    if ($this->validateCacheDir($pOptions['cachedir'])){

		$cachedfile = $pOptions['cachedir'] . "/{$pOptions['cacheid']}_{$pWidth}_{$pHeight}.jpg";

		if (file_exists($cachedfile))
		    $this->create($cachedfile);
		else {
		    $this->create($pFile);
		    $this->process($pWidth, $pHeight, $pCropRatio);
		    $this->save($cachedfile);
		}
	    } else
		$this->process($pWidth, $pHeight, $pCropRatio);
	} else {
	    $this->create($pFile);
	    $this->process($pWidth, $pHeight, $pCropRatio);
	}
	if (array_key_exists('destination', $pOptions))
	    $this->save($pOptions['destination']);

    }

    protected function process($pWidth, $pHeight, $pCropRatio=null){
	$original = $this->image;

	$this->owidth = $this->width;
	$this->oheight= $this->height;

	$owidth = $this->owidth;
	$oheight = $this->height;

// 	logdebug("FP_Image_Thumbnail.process: owidth={$this->width} oheight={$this->height}");

	$offsetx = 0;
	$offsety = 0;

	if ($pCropRatio){
	    $cropRatio = explode(':', $pCropRatio);
	    if (count($cropRatio)){
		$ratioComputed = $owidth / $oheight;
		$cropRatioComputed = (float) $cropRatio[0] / (float) $cropRatio[1];

		if ($ratioComputed < $cropRatioComputed){
		$real_oheight = $oheight;
		$oheight = $owidth / $cropRatioComputed;
		$offsety = ($real_oheight - $oheight) / 2;
		} else if ($ratioComputed > $cropRatioComputed){
		$real_owidth = $owidth;
		$owidth = $oheight * $cropRatioComputed;
		$offsetx = ($real_owidth - $owidth) / 2;
		}
	    }
	}

	$xratio = $pWidth / $owidth;
	$yratio = $pHeight / $oheight;

	if ($xratio * $oheight < $pHeight){
	    $height = ceil($xratio * $oheight);
	    $width = $pWidth;
	} else {
	    $width = ceil($yratio * $owidth);
	    $height = $pHeight;
	}

	$this->image = ImageCreateTrueColor($width, $height);
	imagecopyresampled($this->image, $original, 0, 0, $offsetx, $offsety, $width, $height, $owidth, $oheight);

	$this->width = $width;
	$this->height = $height;

	imagedestroy($original);
    }

    protected function sharpen($pOriginalWidth, $pWidth){ // function from Ryan Rud (http://adryrun.com)
	$pWidth	= $pWidth * (750.0 / $pOriginalWidth);
	$a		= 52;
	$b		= -0.27810650887573124;
	$c		= .00047337278106508946;

	$result = $a + $b * $pWidth + $c * $pWidth * $pWidth;

	$sharpness = max(round($result), 0);

	$sharpenMatrix	= array(
	    array(-1, -2, -1),
	    array(-2, $sharpness + 12, -2),
	    array(-1, -2, -1)
	);
	$divisor = $sharpness;
	$offset = 0;
	imageconvolution($this->image, $sharpenMatrix, $divisor, $offset);
    }
}

?>